from . import news_blue
from flask import request,jsonify,render_template,session,g
from info.models import News,User,Comment,CommentLike
from info.response_code import RET,error_map
from info import db
from info.utils.commons import user_login_data

# 功能: 关注作者
@news_blue.route('/follow_user',methods=["POST"])
@user_login_data
def follow_user():
    # 1,判断用户是否登录
    if not g.user:
        return jsonify(errno=RET.SESSIONERR,errmsg=error_map[RET.SESSIONERR])

    # 2,获取参数
    action = request.json.get("action")
    author_id = request.json.get("author_id")

    # 3,判断是否自己关注自己
    if int(author_id) == g.user.id:
        return jsonify(errno=RET.DATAERR,errmsg=error_map[RET.DATAERR])

    # 4,为空校验
    if not all([action,author_id]):
        return jsonify(errno=RET.NODATA,errmsg=error_map[RET.NODATA])

    # 5,校验action类型
    if action not in ["follow","unfollow"]:
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])

    # 6,判断是关注,还是取消关注
    author = User.query.get(author_id)
    if action == "follow":
        author.followers.append(g.user)
    else:
        author.followers.remove(g.user)

    # 7,提交数据库
    db.session.commit()

    # 8,返回响应
    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK])

# 功能: 评论点赞,取消点赞
@news_blue.route('/comment_like',methods=["POST"])
@user_login_data
def comment_like():
    # 1,判断用户是否登录
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

    # 2,获取请求的参数
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")

    # 3,为空校验
    if not all([comment_id, action]):
        return jsonify(errno=RET.NODATA, errmsg=error_map[RET.NODATA])

    # 4,校验action参数
    if action not in ["add","remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 5,判断是点赞, 还是取消点赞
    if action == "add":
        # 判断用户是否点过赞
        comment_count = CommentLike.query.filter(CommentLike.user_id==g.user.id,CommentLike.comment_id==comment_id).count()
        if comment_count == 0:
            c_like = CommentLike()
            c_like.comment_id = comment_id
            c_like.user_id = g.user.id
            db.session.add(c_like)
            db.session.commit()

            # 修改评论点赞数量
            Comment.query.get(comment_id).like_count += 1
            db.session.commit()
    else:
        # 判断用户是否点过赞
        comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id,
                                                 CommentLike.comment_id == comment_id).first()
        if comment_like:
            # 删除点赞
            db.session.delete(comment_like)
            db.session.commit()
            # 修改评论点赞数量
            Comment.query.get(comment_id).like_count -= 1
            db.session.commit()

    # 6,返回响应
    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK])

# 功能: 新闻评论
@news_blue.route('/news_comment',methods=["POST"])
@user_login_data
def news_comment():
    # 1,判断用户是否登录
    if not g.user:
        return jsonify(errno=RET.SESSIONERR,errmsg=error_map[RET.SESSIONERR])

    # 2,获取请求的参数
    news_id = request.json.get("news_id")
    content = request.json.get("comment")

    # 3,为空校验
    if not all([news_id,content]):
        return jsonify(errno=RET.NODATA,errmsg=error_map[RET.NODATA])

    # 4,创建评论对象
    comment = Comment()
    comment.user_id = g.user.id
    comment.news_id = news_id
    comment.content = content

    # 4,1 判断当前评论是否回复评论
    parent_id = request.json.get("parent_id")
    if parent_id:
        comment.parent_id = parent_id

    # 5,添加数据到数据库
    db.session.add(comment)
    db.session.commit()

    # 6,返回响应
    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK],data=comment.to_dict())

# 功能: 新闻收藏&取消收藏
@news_blue.route('/news_collect',methods=["POST"])
@user_login_data
def news_collect():
    # 1,判断用户是否登录了
    if g.user is None:
        return jsonify(errno=RET.SESSIONERR,errmsg=error_map[RET.SESSIONERR])

    # 2,获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 3,为空校验参数
    if not all([news_id,action]):
        return jsonify(errno=RET.NODATA,errmsg=error_map[RET.NODATA])

    # 4,判断action的状态是否正确
    if action not in ["collect","cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 5,判断action是收藏,还是取消收藏
    if action == "collect":
        # g.user.collection_news = [News.query.get(news_id)]
        g.user.collection_news.append(News.query.get(news_id))
        db.session.commit()
    else:
        g.user.collection_news.remove(News.query.get(news_id))
        db.session.commit()

    # 6,返回响应
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])

# 功能: 新闻详情页面
@news_blue.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):

    # 1,根据新闻编号查询新闻对象
    news = News.query.get(news_id)

    # 2,判断当前用户是否对新闻进行收藏
    is_collected = False
    if g.user:
        if news in g.user.collection_news:
            is_collected = True

    # 3,查询新闻的评论数据
    comments = Comment.query.filter(Comment.news_id==news_id).order_by(Comment.create_time.desc()).all()

    # 4,将评论的对象列表转成字典列表
    comment_list = []
    for comment in comments:
        comment_dict = comment.to_dict()
        # # 查询该条评论所有的子评论
        # sub_comments = Comment.query.filter(Comment.parent_id==comment.id).all()
        #
        # # 子评论字典列表转换
        # sub_comments_list = []
        # for sub_comment in sub_comments:
        #     sub_comments_list.append(sub_comment.to_dict())
        #
        # # 将子评论存储到父评论中
        # comment_dict["sub_comments"] = sub_comments_list

        # 然后将父评论添加到父评论字典列表中

        # 给当前评论添加点赞键值对
        comment_dict["is_like"] = False

        # 判断当前登录的用户是否对该评论点过赞
        # if 当前用户需要是登录状态 and 当前评论在用户点赞过的评论里面:
        if g.user and comment.id in [ck.comment_id for ck in g.user.comment_likes.all()]:
            comment_dict["is_like"] = True

        comment_list.append(comment_dict)

    # 5,判断当前登录的用户是不是新闻作者的粉丝
    is_followed = False
    if g.user and news.user:
        if g.user in news.user.followers:
            is_followed = True

    # 返回响应
    data = {
        "news":news.to_dict(),
        "user_info": g.user.to_dict() if g.user else g.user,
        "is_collected":is_collected,
        "comments":comment_list,
        "is_followed":is_followed
    }
    return render_template('news/detail.html',data=data)

# 功能: 获取新闻列表
@news_blue.route('/newslist')
def news_list():

    # 1,获取请求参数
    page = request.args.get("page")
    cid = request.args.get("cid")
    per_page = request.args.get("per_page")

    # 2,查询新闻对象 [news对象,news对象,news对象] => [字典,字典,字典]
    if cid == "1":
        paginate = News.query.filter(News.status==0).order_by(News.create_time.desc()).paginate(int(page),int(per_page),False)
    else:
        paginate = News.query.filter(News.status==0,News.category_id==cid).order_by(News.create_time.desc()).paginate(int(page),int(per_page),False)

    # 3,获取分页对象中的数据
    totalPage = paginate.pages
    currentPage = paginate.page
    news = paginate.items

    # 3,将news转成json数据
    news_list = []
    for item in news:
        item_dict = item.to_dict()
        news_list.append(item_dict)

    # 3,拼接数据返回页面中
    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK],newsList=news_list,totalPage=totalPage)